<template>
    <Card class="no-border-card">
        <p slot="title">日志</p>

        <Row :gutter="20" class="margin-bottom-20">
            <i-col :span="5" v-if="!isDeviceLog">
                <Select
                    v-model="parentId"
                    placeholder="全部"
                    clearable
                    @on-change="handleOptionChange(1)">
                    <Option
                        v-for="lv1 in lv1Options"
                        :value="lv1.id"
                        :key="lv1.id">
                        {{lv1.name}}
                    </Option>
                </Select>
            </i-col>
            <i-col :span="5">
                <Select
                    v-model="typeCode"
                    placeholder="全部"
                    clearable>
                    <Option
                        v-for="lv2 in lv2Options"
                        :value="lv2.code"
                        :key="lv2.id">
                        {{lv2.name}}
                    </Option>
                </Select>
            </i-col>
            <i-col :span="5">
                <DatePicker
                    :clearable="false"
                    type="daterange"
                    style="width:100%;"
                    v-model="timeRange"
                    placeholder="选择时间段"
                />
            </i-col>
            <Button type="primary" icon="ios-search-strong" style="padding:4px 0px 3px;" @click="handleSearch"></Button>
        </Row>

        <!--日志数据-->
        <Table border stripe :columns="columns" :data="tableData" :loading="loading"></Table>
        <!--日志数据end-->

        <div class="text-center">
            <Page
                show-total
                show-elevator
                :total="pagination.total"
                :page-size="pagination.limit"
                :current.sync="pagination.current"
                @on-change="getOperateData"
            />
        </div>
    </Card>
</template>

<script>
    /**
     * 关联组件: 日志->第三方接口调用记录, 设备详情(门锁, 电表, 水表)->第三方接口调用记录
     */
    import debounce from 'lodash/debounce'
import dataCenter from '@/libs/dataCenter'
import { http, api } from '@/libs/http'
import { twoDaysAgo, now, searchTimeRange, dayTimeStamp, date } from '@/libs/date'

export default {
      name: 'openapi-log',
      props: {
        deviceType: {
          validator: function (value) {
            return [ 'lock', 'elemeter', 'watermeter', 'face-access' ].includes(value)
          }
        },
        deviceId: Number,
        roomId: {
          type: Number,
          default: -1
        }
      },
      data () {
        return {
          loading: false,
          tableData: [],
          typeCode: '',
          parentId: '',
          operationTypes: [],
          timeRange: [ twoDaysAgo, now ],
          pagination: {
            total: 0,
            current: 1,
            limit: 20
          },
          columns: [
            { title: '操作项', key: 'opType', align: 'center', width: 120 },
            { title: '请求ID', key: 'opId', align: 'center', width: 120 },
            { title: '操作者', key: 'opClient', align: 'center', width: 100 },
            { title: '结果', key: 'opResult', align: 'center', width: 100 },
            { title: '范围', key: 'opRange' },
            { title: '说明', key: 'opName' },
            { title: '时间', key: 'date', align: 'center', width: 140 }
          ],
          // 通过结构返回的类型的name来判断具体设备类型
          deviceTypeMap: {
            lock: '门锁',
            elemeter: '电表',
            watermeter: '水表',
            'face-access': '人脸门禁'
          }
        }
      },
      computed: {
        lv1Options () {
          const { operationTypes } = this
          return operationTypes.filter(type => type.parent_ids && type.parent_ids.length === 0)
        },
        lv2Options () {
          const { operationTypes, parentId } = this
          if (!parentId) return []
          return operationTypes.filter(type => type.parent_id === parentId)
        },
        isDeviceLog () {
          return !!this.deviceId
        }
      },
      created () {
        this.getOperationTypes()
        this.getOperateData(1, true)
      },
      methods: {
        handleSearch: debounce(function () {
          this.getOperateData(1, true)
        }, 250),
        handleOptionChange (deep) {
          this.typeCode = ''
        },
        initParentId (types) {
          const { isDeviceLog, deviceTypeMap, deviceType } = this
          if (isDeviceLog) {
            const deviceLogType = types.find(type => type.name === deviceTypeMap[deviceType])
            if (!deviceLogType) return
            this.parentId = deviceLogType.id
          }
        },
        async getOperationTypes () {
          const types = await dataCenter.getOpenapiType()
          this.operationTypes = types
          this.initParentId(types)
        },
        getQuery () {
          const {
            parentId, typeCode, pagination: { limit, current }, deviceId, roomId
          } = this
          const [ start_time, end_time ] = searchTimeRange(this.timeRange)
          const query = {
            start_time,
            end_time,
            limit,
            offset: limit * (current - 1)
          }
          if (typeCode) {
            query.type_code = typeCode
          } else if (parentId) {
            query.parent_id = parentId
          }
          if (deviceId) query.device_id = deviceId
          if (roomId !== -1) query.room_id = roomId
          return query
        },
        async getOperateData (page, recount = false) {
          if (page === 1) this.pagination.current = 1

          const query = this.getQuery()
          const { start_time, end_time } = query
          const monthTimestamp = 30 * dayTimeStamp

          if (!start_time || !end_time || (end_time - start_time > monthTimestamp)) {
            this.$Message.info('查询时间不能大于30天')
            return
          }

          try {
            this.loading = true
            if (recount) this.getOperateDataCount(query)
            const res = await http.req(api.openapi_operations, null, query)
            this.tableData = this.formatListData(res.operations)
          } catch (err) {
            console.log(err)
          } finally {
            this.loading = false
          }
        },
        async getOperateDataCount (query) {
          try {
            const res = await http.req(api.openapi_operations_count, null, query)
            if (res) {
              this.pagination.total = res.count
            }
          } catch (err) {
            console.log(err)
          }
        },
        formatListData (list) {
          return list.map(item => {
            const {
              operation_type: { name: opType } = {},
              target: { name: opRange, value: opName, comment } = {},
              created_at, res_state, req_id, client_id
            } = item
            return {
              opType: opType === '冻结/解冻租客' ? (comment || '-') : opType,
              opId: req_id,
              opClient: client_id,
              opResult: res_state === 1 ? '成功' : `其它(${res_state})`,
              opRange: opRange || '-',
              opName: opName || '-',
              date: date(created_at, 'YYYY-MM-DD HH:mm')
            }
          })
        }
      }
    }
</script>